package com.ttg.common.utils;

import com.ttg.common.constant.BasicConstant;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Objects;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author ZQ
 * @version 1.0
 * @Description
 * @date 2021/2/1 13:57
 */
public class  StringUtil {
    private static final String REG_PHONE_CN = "^1[3456789]\\d{9}$";
    private static final String REG_PHONE_TW = "^0[9]\\d{8}$";
    private static final String REG_PHONE = "^[1-9]\\d*$";
    private static final String REG_EMAIL = "([a-z0-9]*[-_.]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[.][a-z]{2,3}([.][a-z]{2})?";
    private static final String REG_NAME = ".*[`~!@#$%^&*()+=|;<>/?~！@#￥%……&*（）——+|【】‘；：”“’。，、？\\\\]+.*";
    private static final String AMOUNT_PATTERN = "^([1-9]\\d*|0)(\\.\\d{1,2})?$";
    private static final String PATTERN_NUMERIC = "[0-9]*";
    private static final String REG_AZ_OR_NUM = "^[a-zA-Z0-9]+$";
    private static final String REG_AD_NUM= "^\\d+(\\,\\d+)*$";//广告编号格式正则

    private static final String PAI_AUTH_CODE_WXPAY= "^(10|11|12|13|14|15)[0-9]{16}$";
    private static final String PAI_AUTH_CODE_ALIPAY= "^(25|26|27|28|29|30)\\d{14,22}$";
    private static final String PAI_AUTH_CODE_UNIONPAY= "^62\\d+$";

    private static final String CARD_BIN = "^[0-9]{6},[0-9],[0-9]{2},[0-9],[0-9]{8},[\\u4e00-\\u9fa5]+,(信用|借记)卡$";
    private static final String BANK_NO = "^[0-9]{12},[\\u4e00-\\u9fa5]+,[\\u4e00-\\u9fa5]+,[\\u4e00-\\u9fa5]+,[\\u4e00-\\u9fa5]+$";
    private static final String COUPON_CARD_BIN = "^[0-9]{6,9}$";
    //域名正则
    private static final String DOMAIN ="[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\\.?";
    //10位以内纯英文
    private static final String TAG = "[a-zA-Z]{1,10}";
    //校验纯中文
    private static final String CHINESE = "[\\u4e00-\\u9fa5]*";
    //发送消息文件处理方式校验
    private static final String MCT_MSG_FILE = "http:\\/\\/[\\w.]+[\\w\\/]*[\\w.]*\\??[\\w=&\\+\\%]*/is";
    //密码校验（大于8位且必须同时包含字母大写，字母小写，数字）
    private static final String PWD_CHECK = "^(?=.*[0-9].*)(?=.*[A-Z].*)(?=.*[a-z].*).{8,}$";

    //匹配经纬度117.985127,28.479382这种格式
    private static final String LONG_LAT = "^(-?\\d+)(\\.\\d+)?,(-?\\d+)(\\.\\d+)?$";

    private static final String YEAR = "^\\d{4}-\\d{2}-\\d{2}";

    private static final int GB_SP_DIFF = 160;
    // 存放国标一级汉字不同读音的起始区位码
    private static final int[] secPosValueList = { 1601, 1637, 1833, 2078, 2274, 2302, 2433, 2594, 2787, 3106, 3212, 3472, 3635,
            3722, 3730, 3858, 4027, 4086, 4390, 4558, 4684, 4925, 5249, 5600 };
    // 存放国标一级汉字不同读音的起始区位码对应读音
    private static final char[] firstLetter = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',
            'R', 'S', 'T', 'W', 'X', 'Y', 'Z' };

    /**
     * 替换字符
     * @param str
     * @return
     */
    public static String replaceBadStr(String str) {
        if (Objects.isNull(str)) {
            return null;
        }
        return str.trim().replaceAll("\\s","").replace(",","&#44;").replace("|","&#124;");
    }

    /**
     * 检查IP地址
     */
    public static boolean isIPAddress(String str) {
        String regex = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}";
        // 判断ip地址是否与正则表达式匹配
        if (str.matches(regex)) {
            String[] arr = str.split("\\.");
            for (int i = 0; i < 4; i++) {
                int temp = Integer.parseInt(arr[i]);
                //如果某个数字不是0到255之间的数 就返回false
                if (temp < 0 || temp > 255) {
                    return false;
                }
            }
            return true;
        }else {
            return false;
            }
    }

    /**
     * 检查手机号
     * @param str
     * @return 正确返回ture,格式错误返回false
     */
    public static boolean checkPhone(String str,String lang) {
        if (StringUtils.isBlank(lang)) {
            lang = BasicConstant.LANG_ZH_CN;
        }
        try {
            if (BasicConstant.LANG_ZH_CN.equals(lang)) {
                return Pattern.matches(REG_PHONE_CN,str);
            } else if (BasicConstant.LANG_ZH_TW.equals(lang)) {
                return Pattern.matches(REG_PHONE_TW,str);
            } else {
                return Pattern.matches(REG_PHONE,str);
            }
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 邮箱校验
     * @param str
     * @return 正确返回ture,格式错误返回false
     */
    public static boolean checkEmail(String str) {
        try {
            return Pattern.matches(REG_EMAIL,str);
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 非空去首尾空白
     * @param str
     * @return
     */
    public static String trim(String str) {
        return StringUtils.isNotBlank(str)? str.trim():null;
    }

    /**
     * 验证数字，带小数也可以
     * @param str 待验证的字符串
     * @return 如果是符合格式的字符串,返回 <b>true </b>,否则为 <b>false </b>
     */
    public static boolean decimalCheck(String str) {
        if (StringUtils.isBlank(str)) {
            return false;
        }
        String regex = "-?[0-9]+(.?[0-9]+)?";
        return match(regex, str);
    }

    /**
     * 验证数字输入
     * @param str 待验证的字符串
     * @return 如果是符合格式的字符串,返回 <b>true </b>,否则为 <b>false </b>
     */
    public static boolean isNumber(String str) {
        if (StringUtils.isBlank(str)) {
            return false;
        }
        String regex = "^[0-9]*$";
        return match(regex, str);
    }

    /**
     * @param regex 正则表达式字符串
     * @param str 要匹配的字符串
     * @return 如果str 符合 regex的正则表达式格式,返回true, 否则返回 false;
     */
    public static boolean match(String regex, String str) {
        if (null == regex || null == str) {
            return false;
        }
        try {
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(str);
            return matcher.matches();
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 非空对象转toString
     * @param o
     * @return
     */
    public static String toStringOrNull(Object o){
        String str = null;
        if (null != o) {
            str = o.toString();
        }
        return str;
    }

    /**
     * 生成uuid
     * @return
     */
    public static String getUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    /**
     * 检查特殊字符
     * @param str
     * @return
     */
    public static boolean checkIllegalChar(String str) {
        try {
            return Pattern.matches(REG_NAME,str);
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 匹配纯数字字母
     * @param str
     * @return
     */
    public static boolean checkAZOrNum(String str) {
        try {
            return Pattern.matches(REG_AZ_OR_NUM,str);
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 检查金额符合0.00格式并且大于0.00
     * @param amount 金额
     * @return boolean
     */
    public static boolean checkAmount(String amount){
        boolean status;
        try {
            status =  Pattern.matches(AMOUNT_PATTERN,amount);
        } catch (Exception e) {
            return false;
        }
        if (!status) {return false;}
        BigDecimal num = new BigDecimal(amount);
        return num.compareTo(new BigDecimal(0)) > 0;
    }
    public static boolean checkAmountQutoa(String amount){
        boolean status;
        try {
            status =  Pattern.matches(AMOUNT_PATTERN,amount);
        } catch (Exception e) {
            return false;
        }
        if (!status) {return false;}
        BigDecimal num = new BigDecimal(amount);
        return num.compareTo(new BigDecimal(500)) > 0;
    }

    /**
     * 判断是否是数字
     */
    public static boolean isNumeric(String string){
        try {
            return Pattern.matches(PATTERN_NUMERIC,string);
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 验证是否是URL
     * @param url
     * @return
     */
    public static boolean verifyUrl(String url){

        // URL验证规则
        String regEx ="[a-zA-z]+://[^\\s]*";
        // 编译正则表达式
        Pattern pattern = Pattern.compile(regEx);
        // 忽略大小写的写法
        // Pattern pat = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(url);
        // 字符串是否与正则表达式相匹配
        boolean rs = matcher.matches();
        return rs;

    }
    /**
     * 校验广告投放 渠道 商户 行业 地区 机构 编号校验
     * @param str
     * @return
     */
    public static boolean checkAdMenu(Object str) {
        try {
            return Pattern.matches(REG_AD_NUM,String.valueOf(str));
        } catch (Exception e) {
            return false;
        }
    }
    /**
     * 校验派派支付渠道 微信
     * @param str
     * @return
     */
    public static boolean checkPaiWx(Object str) {
        try {
            return Pattern.matches(PAI_AUTH_CODE_WXPAY,String.valueOf(str));
        } catch (Exception e) {
            return false;
        }
    }
    /**
     * 校验派派支付渠道 阿里
     * @param str
     * @return
     */
    public static boolean checkPaiAl(Object str) {
        try {
            return Pattern.matches(PAI_AUTH_CODE_ALIPAY,String.valueOf(str));
        } catch (Exception e) {
            return false;
        }
    }


    /**
     * 校验派派支付渠道 UNIONPAY
     * @param str
     * @return
     */
    public static boolean checkPaiUN(Object str) {
        try {
            return Pattern.matches(PAI_AUTH_CODE_UNIONPAY,String.valueOf(str));
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 校验n位数字
     * @param str
     * @return
     */
    public static boolean checkCardBin(Object str){
        try {
            return Pattern.matches(CARD_BIN,String.valueOf(str));
        }catch (Exception e){
            return false;
        }
    }

    /**
     * 校验联行号
     * @param str
     * @return
     */
    public static boolean checkBankNo(Object str){
        try {
            return Pattern.matches(BANK_NO,String.valueOf(str));
        }catch (Exception e){
            return false;
        }
    }

    /**
     * 校验优惠券支付方式卡BIN
     */
    public static boolean checkCouponCardBin(Object str){
        try {
            return Pattern.matches(COUPON_CARD_BIN,String.valueOf(str));
        }catch (Exception e){
            return false;
        }
    }

    /**
     * 效验域名
     */
    public static boolean checkDomain(Object str){
        try {
            return Pattern.matches(DOMAIN,String.valueOf(str));
        }catch (Exception e){
            return false;
        }
    }

    /**
     * 标签校验，10位以内纯英文
     */
    public static boolean checkTag(Object str){
        try {
            return Pattern.matches(TAG,String.valueOf(str));
        }catch (Exception e){
            return false;
        }
    }

    /**
     * 校验纯中文
     */
    public static boolean checkChinese(Object str){
        try {
            return Pattern.matches(CHINESE,String.valueOf(str));
        }catch (Exception e){
            return false;
        }
    }

    /**
     * 发送消息文件处理方式校验
     */
    public static boolean checkMctMsgFile(Object str){
        try {
            return Pattern.matches(MCT_MSG_FILE,String.valueOf(str));
        }catch (Exception e){
            return false;
        }
    }

    /**
     * 匹配经纬度117.985127,28.479382这种格式
     */
    public static boolean checkLongAndLat(String str){
        try {
            return Pattern.matches(LONG_LAT,str);
        }catch (Exception e){
            return false;
        }
    }

    /**
     * 字符串 yyyy-MM-dd 格式校验
     */
    public static boolean checkYear(String str){
        try {
            return Pattern.matches(YEAR,str);
        }catch (Exception e){
            return false;
        }
    }

    /**
     * 提取汉字字符串的首字母
     * @param characters 汉字字符串
     * @return
     */
    public static String getSpells(String characters) {
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < characters.length(); i++) {

            char ch = characters.charAt(i);
            if ((ch >> 7) == 0) {
                // 判断是否为汉字，如果左移7为为0就不是汉字，否则是汉字
                buffer.append(ch);
            } else {
                char spell = getFirstLetter(ch);
                buffer.append(String.valueOf(spell));
            }
        }
        return buffer.toString();
    }

    /**
     * 获取一个汉字的首字母
     * @param ch 汉字
     * @return
     */
    public static Character getFirstLetter(char ch) {

        byte[] uniCode = null;
        try {
            uniCode = String.valueOf(ch).getBytes("GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
        if (uniCode[0] < 128 && uniCode[0] > 0) { // 非汉字
            return null;
        } else {
            return convert(uniCode);
        }
    }

    /**
     * 获取一个汉字的拼音首字母。 GB码两个字节分别减去160，转换成10进制码组合就可以得到区位码
     * 例如汉字“你”的GB码是0xC4/0xE3，分别减去0xA0（160）就是0x24/0x43
     * 0x24转成10进制就是36，0x43是67，那么它的区位码就是3667，在对照表中读音为‘n’
     */
    private static char convert(byte[] bytes) {
        char result = '#';
        int secPosValue = 0;
        int i;
        for (i = 0; i < bytes.length; i++) {
            bytes[i] -= GB_SP_DIFF;
        }
        secPosValue = bytes[0] * 100 + bytes[1];
        for (i = 0; i < 23; i++) {
            if (secPosValue >= secPosValueList[i] && secPosValue < secPosValueList[i + 1]) {
                result = firstLetter[i];
                break;
            }
        }
        return result;
    }
}
